package com.timer.taskRule.controller;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class FileAlterationMonitorInstances {

    private FileAlterationMonitor monitor = null;
    /***
     * 监控路径
     */
    private String rootDir = null;
    /***
     * 监控频率
     */
    private long interval = TimeUnit.SECONDS.toMillis(1);
    /***
     * 过滤器
     */
    private List<IOFileFilter> filters = null;

    /***
     * 监听类
     */
    private FileAlterationListener listener = null;

    public FileAlterationMonitorInstances(String rootDir, long interval,FileAlterationListener listener, String... fileType) {
        this.rootDir = rootDir;
        this.interval = interval;
        this.listener = listener;
        this.filters = new ArrayList<>();
        for (String s : fileType) {
            IOFileFilter files = FileFilterUtils.and(
                    FileFilterUtils.fileFileFilter(),
                    FileFilterUtils.suffixFileFilter(s));
            filters.add(files);
        }
    }


    public FileAlterationMonitorInstances(String rootDir, long interval,FileAlterationListener listener) {
        this.rootDir = rootDir;
        this.interval = interval;
        this.listener = listener;
    }

    public FileAlterationMonitorInstances(String rootDir,FileAlterationListener listener) {
        this.rootDir = rootDir;
        this.listener = listener;
    }

    public FileAlterationMonitor monitor(){
        IOFileFilter filter = this.filters == null ? null : FileFilterUtils.or(this.filters.toArray(new IOFileFilter[this.filters.size()]));
        FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir),filter);
        observer.addListener(listener);
        return new FileAlterationMonitor(interval, observer);
    }
}
